import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('127.0.0.1'))
channel = connection.channel()

# 避免交换机未创建
channel.exchange_declare(exchange='logs',  # 交换机名称
                         exchange_type='fanout')  # 模式---发布订阅

result = channel.queue_declare('', exclusive=True)  # 声明一个独占队列，队列名称由服务器自动生成，并返回给消费者
queue_name = result.method.queue  # 获取队列名

# 把队列绑定到交换机
channel.queue_bind(exchange='logs', queue=queue_name)


def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)


# 监听队列（配置，还未监听，只是确认）
channel.basic_consume(queue=queue_name,
                      auto_ack=True,
                      on_message_callback=callback)

print(" [*] Waiting for")
channel.start_consuming()  # 开始消费
